package trade.axht.util;

import java.io.IOException;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

public class QiniuUtils {
    //设置好账号的ACCESS_KEY和SECRET_KEY
    String ACCESS_KEY = "pl0g51dJ1l_kza8VsIktXlNmxCdy-vVqWvBM5Acy";
    String SECRET_KEY = "2Joozy3gqII68oY2xB5tKffR5z-TfUJSJR86__DF";
    //要上传的空间
    String bucketname = "axht";

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    UploadManager uploadManager = new UploadManager();

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken(){
        return auth.uploadToken(bucketname);
    }

    public void upload(byte[] file,String key) throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(file, key, getUpToken());
            //打印返回的信息
            System.out.println(res.bodyString());
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
            } catch (QiniuException e1) {
                //ignore
            }
        }
    }

    /**
     * 上传文件
     * @param file byte
     * @param key 文件名
     * @throws Exception
     */
    public void uploadFile(byte[] file,String key) throws Exception{
        new QiniuUtils().upload(file,key);
    }
}